#include "histogram.h"
#include <opencv2/legacy/legacy.hpp>

std::vector<double> CalcHistogram(const cv::Mat &img, int bins, const float range_min, const float range_max)
{
	float range[] = {range_min, range_max};
	float *ranges[] = { range };

	CvHistogram *hist = cvCreateHist(1, &bins, CV_HIST_ARRAY, ranges, 1);
	cvClearHist(hist);
	IplImage ipl_img = img;
	IplImage *p_ipl_img = &ipl_img;
	cvCalcHist(&p_ipl_img, hist, 0, 0);

	float max = 0;
	cvGetMinMaxHistValue(hist, 0, &max);

	std::vector<double> res(bins);
	for (int i = 0; i < bins; ++i)
	{
		double value = cvGetReal1D(hist->bins, i);
		res[i] = value/max;
	}
	return res;
}

cv::Mat DrawHistogram(const std::vector<double> &hist, const int threshould)
{
	const int bins = static_cast<int>(hist.size());
	cv::Mat res(255, bins, CV_8UC1, cv::Scalar(0));
	for (int i = 0; i < bins; ++i)
	{
		cv::line(res, cv::Point(i, 255), cv::Point(i, 255*(1 - hist[i])), cv::Scalar(255));
	}
	cv::line(res, cv::Point(threshould, 0), cv::Point(threshould, 255), RGB(255, 0, 0));
	return res;
}